package algorithms.que13;

import edu.princeton.cs.algs4.In;
import edu.princeton.cs.algs4.StdOut;

import java.util.Iterator;

/**
 * @功能
 * @创建时间 2020/8/1
 */
public class Stack1<Item> implements Iterable<Item>
{
    private int N;
    private Node first;
    private int pushPopCount;

    private class Node
    {
        Item item;
        Node next;
    }

    public Stack1()
    {
    }

    public Stack1(Stack s)
    {
        Node right=new Node();
        Node oldright;
        for(Object i:s)
        {
            oldright=right;
            right=new Node();
            right.item=(Item) i;
            right.next=null;
            if(isEmpty())
                first=right;
            else
                oldright.next=right;
            N++;
        }
    }
    public boolean isEmpty()
    {return N==0;}

    public int size()
    {return N;}

    public void push(Item item)
    {
        Node oldfirst=first;
        first=new Node();
        first.item=item;
        first.next=oldfirst;
        N++;
        pushPopCount++;
    }

    public Item pop()
    {
        Item item=first.item;
        first=first.next;
        N--;
        pushPopCount++;
        return item;
    }


    public Item peek()
    {
        Item item=first.item;
        return item;
    }

    public void catenation(Stack s)
    {
        while(!s.isEmpty())
        {
            this.push((Item)s.pop());
        }
    }

    public Iterator<Item> iterator()
    {return new ListIterator();}

    private class ListIterator implements Iterator<Item>
    {
        private Node current=first;
        private int originatedPushPopCount;
        public ListIterator()
        {
            originatedPushPopCount=pushPopCount;
        }
        public boolean hasNext(){return current!=null;}
        public void remove(){}
        public Item next()
        {
            if(originatedPushPopCount!=pushPopCount)
                throw new java.util.ConcurrentModificationException();
            Item item=current.item;
            current=current.next;
            return item;
        }//end next
    }//end class ListIterator

    public static void main(String[] args)
    {
        Stack1<String> s1=new Stack1<String>();
        In in1=new In(args[0]);
        while(!in1.isEmpty())
        {
            String item=in1.readString();
            s1.push(item);
        }//end while

        //
        for(String item:s1)
        {
            StdOut.println(item+" ");
            s1.push("push a element");
        }
    }
}
